<template>
  <div class="content-container">
    <el-row
      type="flex"
      justify="space-between"
      class="header-filter four-border-blueBg"
    >
      <div class="row-left">
        <SelectOrganize
          v-if="userInfo.superAdmin"
          v-model="listParams.tenantId"
          class="item"
          :placeholder="$t('userCenter.selectOrganize')"
          clearable
        />
        <TextInput
          v-model="listParams.deptName"
          class="item"
          :placeholder="$t('userCenter.deptName')"
          clearable
        />
        <el-button type="primary" @click="handleQuery">{{
          $t('public.search')
        }}</el-button>
        <el-button plain @click="handleReset">{{
          $t('public.reset')
        }}</el-button>
      </div>
      <div class="row-right">
        <el-button type="primary" @click="handleCreate"
          >+ {{ $t('public.create') }}</el-button
        >
      </div>
    </el-row>
    <div class="base-table-container">
      <BaseTable
        ref="refContentTable"
        v-loading="loading"
        :data="tableData"
        row-key="deptId"
        default-expand-all
        :tree-props="{
          children: 'childDeptList'
        }"
      >
        <TableColumn
          prop="deptName"
          :label="$t('userCenter.deptName')"
          :column-width="columnWidthObj.deptName"
        />
        <TableColumn
          prop="deptOrder"
          :label="$t('userCenter.displayOrder')"
          :column-width="columnWidthObj.deptOrder"
        />
        <!-- <TableColumn
          prop="deptId"
          :label="$t('userCenter.deptId')"
          :column-width="columnWidthObj.deptId"
        /> -->
        <TableColumn
          prop="createTime"
          :label="$t('public.createTime')"
          :column-width="columnWidthObj.createTime"
        />
        <TableColumn
          prop="action"
          fixed="right"
          :label="$t('public.action')"
          :column-width="columnWidthObj.action"
        >
          <template #default="{ row }">
            <el-button v-if="row.parentId" text @click="handleEditDialog(row)">
              {{ $t('public.edit') }}
            </el-button>
            <el-button text @click="handleCreate(row)">
              {{ $t('public.create') }}
            </el-button>
            <el-button v-if="row.parentId" text @click="handleDelete(row)">
              {{ $t('public.delete') }}
            </el-button>
          </template>
        </TableColumn>
      </BaseTable>
    </div>
    <!-- 新建 -->
    <AddDialog
      v-if="addVisible"
      v-model="addVisible"
      :dept-id="deptId"
      @update="handleQuery"
    />
    <!-- 编辑 -->
    <EditDialog
      v-if="editVisible"
      v-model="editVisible"
      :row="tableRow"
      :dept-id="deptId"
      @update="handleQuery"
    />
  </div>
</template>

<script setup>
import AddDialog from './component/AddDialog.vue'
import EditDialog from './component/EditDialog.vue'

const { userInfo } = storeToRefs(useUserStore())
const listParams = ref({
  tenantId: '',
  deptName: ''
})
const refContentTable = ref(null)
const loading = ref(false)
const allTableData = ref([])
const tableData = ref([])
const columnWidthObj = ref({})
const addVisible = ref(false)
const deptId = ref('')
const tableRow = ref({})
const editVisible = ref(false)

watch(
  () => listParams.value.deptName,
  nv => {
    filterTableList()
  }
)

const getTableList = () => {
  loading.value = true
  tableData.value = []
  g_api.userCenter
    .apiDeptList({
      ...listParams.value
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        allTableData.value = data
        filterTableList()
        deptId.value = tableData.value[0].deptId
        // console.log('deptId.value', deptId.value)
        useTableColumnWidth({
          refTable: refContentTable.value
        }).getTableColumnWidth(data => {
          columnWidthObj.value = data
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 过滤表格数据
const filterTreeData = (data, filterText) => {
  return data
    .map(item => {
      if (item.childDeptList) {
        item.childDeptList = filterTreeData(item.childDeptList, filterText)
        return item.childDeptList.length || item.deptName.includes(filterText)
          ? item
          : null
      } else {
        return item.deptName.includes(filterText) ? item : null
      }
    })
    .filter(Boolean)
}

const filterTableList = () => {
  tableData.value = filterTreeData(
    JSON.parse(JSON.stringify(allTableData.value)),
    listParams.value.deptName
  )
}

onMounted(() => {
  getTableList()
})

const handleQuery = () => {
  getTableList()
}

const handleReset = () => {
  Object.assign(listParams.value, {
    tenantId: '',
    deptName: ''
  })
  handleQuery()
}

const handleCreate = row => {
  addVisible.value = true
  deptId.value = row.deptId || tableData.value[0].deptId
}

const handleEditDialog = row => {
  editVisible.value = true
  tableRow.value = row
  deptId.value = row.deptId
}

const handleDelete = row => {
  g_utils
    .deleteConfirm()
    .then(() => {
      loading.value = true
      g_api.userCenter
        .apiDeptDelete({
          deptId: row.deptId
        })
        .then(res => {
          if (res.code === '200') {
            ElMessage.success(res.message)
            handleQuery()
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}
</script>

<style lang="scss" scoped></style>
